<template>
  <a-space direction="vertical">
    <a-card title="交易报文选择项配置">
      <a-form ref="searchRef" name="searchBar" :model="searchFormState" :labelCol="{ span: 5, offset: 1 }"
        @finish="handleSearch">
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item name="chooseGroupId" label="选择组名称">
              <a-select v-model:value="searchFormState.chooseGroupId" placeholder="选择组名称" :loading="groupLoading"
                allowClear showSearch
                :filterOption="(inputValue: string, option: any) => filterGroup(inputValue, option, groupList)"
                @change="handleSearchFormGroupChange">
                <!-- 遍历选择组编号列表生成选项 -->
                <a-select-option v-for="group in groupList" :key="group.chooseGroupId" :value="group.chooseGroupId">
                  {{ group.chooseGroupName || '未命名组' }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item name="chooseOptionName" label="选择项名称">
              <a-input v-model:value="searchFormState.chooseOptionName" placeholder=""></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24" style="text-align: right">
            <a-button type="primary" html-type="submit" :loading="searchLoading">搜索</a-button>
            <a-button style="margin: 0 8px" @click="() => searchRef?.resetFields()">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card>
      <a-space>
        <a-button @click="showModal" type="primary"><template #icon> <appstore-add-outlined /> </template>新增</a-button>
        <a-button @click="showEditModal"
          style="background-color: #f6ffed; color: #237804; border-color: #b7eb8f"><template #icon> <form-outlined />
          </template>修改</a-button>
        <a-button @click="showDelete" type="primary" danger><template #icon> <delete-outlined />
          </template>删除</a-button>
      </a-space>
    </a-card>
    <a-card title="查询结果">
      <a-table class="ant-table-striped" :rowClassName="
            (_record: any, index: number) => (index % 2 === 1 ? 'table-striped' : null)
          " :columns="columns" :data-source="data" rowKey="id" :loading="searchLoading" :rowSelection="rowSelection"
        @change="
            (pagination: any) => {
              handleSearch(pagination);
            }
          " :pagination="{
            position: [`bottomRight`],
            showSizeChanger: true,
            showQuickJumper: true,
            current: pageNum,
            pageSize,
            total: total,
            showTotal: (total: any) => `总计 ${total} 条记录`,
          }">
        <template #bodyCell="{ column, text }">
          <template v-if="column.dataIndex === 'name'">
            <a>{{ text }}</a>
          </template>
        </template>
      </a-table>
    </a-card>
    <a-modal ref="modalRef" v-model:visible="visible" @ok="handleOk" style="width: 1200px; top: 0">
      <template #title>
        <div ref="modalTitleRef" style="width: 100%; cursor: move">
          {{ currentAction }}交易报文选择项
        </div>
      </template>

      <a-form ref="formRef" :model="formState" :labelCol="{ span: 5, offset: 1 }" name="form_in_modal">
        <a-row :gutter="24">
          <!-- 选择组编号：根据是否有值切换禁用状态 -->
          <a-col :span="14" :offset="6">
            <a-form-item name="chooseGroupId" label="选择组编号" :rules="[{ required: true, message: '请选择选择组编号' }]">
              <a-select v-model:value="formState.chooseGroupId" placeholder="请选择选择组编号" :loading="groupLoading"
                allowClear showSearch
                :filterOption="(inputValue: string, option: any) => filterGroup(inputValue, option, groupList)"
                @change="(val: string) => handleModalGroupChange(val, groupList, formState)"
                :disabled="!!formState.chooseGroupId && isSearchGroupSelected">
                <a-select-option v-for="group in groupList" :key="group.chooseGroupId" :value="group.chooseGroupId">
                  {{ group.chooseGroupId || '未命名组' }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!-- 自动映射的组名称（只读显示） -->
          <a-col :span="14" :offset="6">
            <a-form-item name="chooseGroupName" label="选择组名称" :rules="[{ required: true, message: '选择组名称不能为空' }]">
              <a-input v-model:value="formState.chooseGroupName" placeholder="选择组编号后自动填充" readonly
                :disabled="!!formState.chooseGroupId && isSearchGroupSelected" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="14" :offset="6">
            <a-form-item name="chooseOptionId" label="选择项编号" :rules="[{ required: true, message: '请输入选择项编号' }]">
              <a-input v-model:value="formState.chooseOptionId" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="14" :offset="6">
            <a-form-item name="chooseOptionName" label="选择项名称" :rules="[{ required: true, message: '请输入选择项名称' }]">
              <a-input v-model:value="formState.chooseOptionName" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="14" :offset="6">
            <a-form-item name="chooseOptionSort" label="顺序号" :rules="[
              { required: false},
              // 自定义正则校验：仅允许数字（整数/小数），适配字符串类型
              { pattern: /^[0-9]+(\.[0-9]+)?$/, message: '请输入有效的数字' }
            ]">
              <a-input v-model:value="formState.chooseOptionSort" type="number" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </a-space>
</template>
  <script lang="ts" setup>
  // base library
  import { LISTHEADER } from "./config"; // 从同级config.ts文件中导入表头
  import { listQuery, add, edit, del} from "@/api/pmManagement/pmChooseOption/pmChooseOption";
  import { getInfo} from "@/api/pmManagement/pmChooseGroup/pmChooseGroup";
  import { fetchGroupList, GroupItem, filterGroup,handleModalGroupChange} from "@/utils/utils"; // 导入公共方法和接口
  import { onMounted } from "@vue/runtime-core";
  import {
    computed,
    createVNode,
    reactive,
    ref,
    toRaw,
    unref
  } from "vue";
  import { FormInstance, message, Modal } from "ant-design-vue";
  import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
  import { useRoute } from 'vue-router';

  // 初始化路由实例获取参数
  const route = useRoute();  
  const searchRef = ref<FormInstance>();
  let searchLoading = ref(true);
  const searchFormState: { [propName: string]: any } = reactive({});
  
  const columns = LISTHEADER;
  let pageNum = ref(1);
  let pageSize = ref(10);
  let total = ref(0);
  let data = ref([]);

  // 选择组列表
  const groupList = ref<GroupItem[]>([]);
  // 加载选择组列表的loading状态
  const groupLoading = ref(false);
  // 标记搜索框是否已选择选择组（控制弹窗禁用状态）
  const isSearchGroupSelected = ref(false);

  // 搜索框选择组变更：仅更新搜索表单状态
  const handleSearchFormGroupChange = (chooseGroupId: string) => {
    searchFormState.chooseGroupId = chooseGroupId;
    isSearchGroupSelected.value = !!chooseGroupId;
  };

  const handleSearch = (values?: any) => {
    searchLoading.value = true;
    console.log("Received values of form: ", values);
    console.log("searchFormState: ", searchFormState);
    let parameter = { ...searchFormState };
    if (values?.current) {
      // 分页切换
      pageNum.value = values?.current;
      pageSize.value = values?.pageSize;
    } else {
      // 搜索
      selectedRowKeys.value = [];
      selectedRows.value = [];
      pageNum.value = 1;
    }
    const requestParameters = Object.assign({}, parameter, {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    });
    console.log("loadData request parameters:", requestParameters);
  
    // 列表查询及条件查询
    listQuery(requestParameters).then(
      (res: {
        code: number | string;
        msg: string;
        total: number;
        rows: any;
      }) => {
        console.log("打印完整的返回信息：" + res);
        searchLoading.value = false;
        const { code, msg, total: count, rows } = res;
        console.log("接口编码：" + code);
        console.log("接口信息：" + JSON.stringify(rows, null, 2))
        if (code === 200) {
          data.value = rows;
          total.value = count;
        } else {
          total.value = 0;
          data.value = [];
          pageNum.value = 1;
          message.error(msg);
        }
      }
    );
  };
  type T = any  
  // 查询出的数据表单展示后，选择数据，对选中的数据进行赋值
  const selectedRowKeys = ref<string[]>([]); // 一般存放选中数据的id，由rowKey控制，rowKey取啥字段就存啥字段的值
  const selectedRows = ref<T[]>([]); // 存放选中行的所有数据
  const onSelectChange = (changableRowKeys: string[], changableRows: T[]) => {
    console.log("选中的行ID:", selectedRowKeys);
    console.log("选中的行数据:", selectedRows);
    console.log("selectedRowKeys changed: ", changableRowKeys);
    selectedRowKeys.value = changableRowKeys;
    selectedRows.value = changableRows;
  };
  const rowSelection = computed(() => {
    return {
      selectedRowKeys: unref(selectedRowKeys),
      onChange: onSelectChange,
      hideDefaultSelections: false,
    };
  });
  enum action {
    add = "新增",
    edit = "编辑",
  }
  const currentAction = ref(action.add);
  const visible = ref<boolean>(false);
  const modalTitleRef = ref<HTMLElement>();
  
  // 表单字段定义，一般是弹窗中的表单
  interface FormValues {
    id: string;
    chooseOptionId: string,
    chooseOptionName: string,
    chooseOptionSort: string,        
    chooseGroupId: string;
    chooseGroupName: string;
    remarks: string;
  }
  const formRef = ref<FormInstance>();
  const formState = reactive<FormValues>({ // 表单数据初始化
    id: "",
    chooseOptionId: "",
    chooseOptionName: "",
    chooseOptionSort: "",    
    chooseGroupId: "",
    chooseGroupName: "",
    remarks: "",
  });
 // 备份初始化为空的表单数据，用于新增按钮时置空可能存在的遗留表单数据
  const formBackup = { ...formState };
  const reset = () => {
    formRef.value?.resetFields();
    Object.assign(formState, formBackup);
    isSearchGroupSelected.value = !!searchFormState.chooseGroupId;    
  }
  // 新增弹窗页面，并对表单数据进行初始化为空，防止出现先打开编辑弹窗后，遗留表单数据
  const showModal = () => {
    reset();
    // 从搜索表单获取选中的选择组编号
    const selectedGroupId = searchFormState.chooseGroupId || "";
    // 搜索框选中时：赋值编号+映射名称+禁用字段
    if (selectedGroupId) {
      formState.chooseGroupId = selectedGroupId;
      const selectedGroup = groupList.value.find(group => group.chooseGroupId === selectedGroupId);
      formState.chooseGroupName = selectedGroup?.chooseGroupName || '';
      isSearchGroupSelected.value = true;
    } else {
      // 未选中时：清空字段+启用选择
      formState.chooseGroupId = "";
      formState.chooseGroupName = "";
      isSearchGroupSelected.value = false;
    }
    formState.id = "";//resetFields() 对 id 字段无效！因为弹窗表单中没有 id 对应的表单控件,手动重置id，双重保障  
    visible.value = true;
    currentAction.value = action.add;
  };
  // 编辑弹窗页面
  const showEditModal = () => {
    if (selectedRowKeys.value.length > 1)
      message.error("仅能选择一条记录进行操作");
    if (selectedRowKeys.value.length === 0)
      message.error("请选择一条记录进行操作");
    if (selectedRowKeys.value.length === 1) {
      currentAction.value = action.edit;
      visible.value = true;
      formRef.value?.resetFields();
      const selectedRow = selectedRows.value[0];
      // 渲染【编辑】弹窗中的数据
      Object.assign(formState, selectedRow);
      // 编辑时强制禁用选择组字段（不可修改）
      isSearchGroupSelected.value = true;   
    }
  };
  // 弹窗页面中确定按钮点击事件，由于新增和修改共用一个弹窗页面，故可以在此方法中判断新增和更新方法
  const handleOk = (e: MouseEvent) => {
    console.log(e);
    // visible.value = false;
    formRef.value
      .validateFields()
      .then((values) => {
        console.log("Received values of form: ", values);
        console.log("formState: ", toRaw(formState));
        visible.value = false;
        // 当前action为add时，调用新增方法add
        if (currentAction.value === action.add) {
          add(formState).then((res) => {
            const { code, msg } = res;
            if (code === 200) {
              Modal.success({
                title: msg,
              });
              formRef.value?.resetFields();
              console.log("reset formState: ", toRaw(formState));
            } else {
              Modal.error({
                title: msg,
              });
            }
            handleSearch();
          });
        }
        // 当前action为edit时，调用编辑方法edit
        if (currentAction.value === action.edit) {
          edit(formState).then((res) => {
            const { code, msg } = res;
            if (code === 200) {
              Modal.success({
                title: msg,
              });
              formRef.value?.resetFields();
              console.log("reset formState: ", toRaw(formState));
            } else {
              Modal.error({
                title: msg,
              });
            }
            handleSearch();
          });
        }
      })
      .catch((info) => {
        console.log("Validate Failed:", info);
      });
  };
  // 删除弹窗页面，选中数据后，点击删除，调用del删除方法
  const showDelete = () => {
    if (selectedRowKeys.value.length === 0){
      message.error("请选择一条记录进行操作");
    } else {
      Modal.confirm({
        title: "请确认是否操作删除?",
        icon: createVNode(ExclamationCircleOutlined),
        okText: "删除",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          console.log("selectedRows: ", toRaw(selectedRows.value[0]).id,selectedRows);
          del(selectedRowKeys.value).then((res) => {
            const { code, msg } = res;
            if (code === 200) {
              console.log("resp: ", toRaw(res));
              Modal.success({
                title: msg,
              });
              handleSearch();
            } else {
              Modal.error({
                title: msg,
              });
            }
          });
        },
        onCancel() {
          console.log("Cancel");
        },
      });
    }
  };
  onMounted(() => {
    searchLoading.value = false;
    fetchGroupList(groupList,groupLoading).then(() => {
      // 获取路由参数中的id
      const id = route.query.id;
      if (id) {
        // 根据id查询对应的选择组名称
        getInfo(id).then((res) => {
          if (res.code === 200) {
            // 将获取到的chooseGroupId设置到搜索表单
            searchFormState.chooseGroupId = res.data.chooseGroupId;
            isSearchGroupSelected.value = !!res.data.chooseGroupId;            
            // 执行初始化查询
            handleSearch();
          }
        });
      }
    });    
    //   handleSearch();
  });
  </script>
  <script lang="ts">
  import {
    AppstoreAddOutlined,
    FormOutlined,
    DeleteOutlined,
  } from "@ant-design/icons-vue";
  
  export default {
    name: "userConfig",
    components: {
      AppstoreAddOutlined,
      FormOutlined,
      DeleteOutlined,
    },
  };
  </script>
  
  <style type="less" scoped>
  /* .ant-form-item-label > label {
    width:150px!important;
    justify-content: end!important;
  } */
  .ant-table-striped :deep(.table-striped) td {
    background-color: #fafafa;
  }
  
  </style>
  